package com.user.servlet;

import com.user.entity.Users;
import com.user.service.IUserService;
import com.user.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "UserRegisterServlet", value = "/UserRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        String schoolidtemp = request.getParameter("schoolid");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (!("".equals(schoolidtemp) && "".equals(username) && "".equals(password))) {

            int schoolid = Integer.parseInt(schoolidtemp);
            Users users = new Users(username, password, schoolid);
            IUserService userService = new UserServiceImpl();
            if (userService.queryUsernameIsExist(users)) {
                request.setAttribute("msg", "用户名存在请输入其他用户名！");
                request.getRequestDispatcher("User/signup.jsp").forward(request, response);
            } else if (!userService.querySchoolidIsExist(users)) {
                request.setAttribute("msg", "该学校号未合作！");
                request.getRequestDispatcher("User/signup.jsp").forward(request, response);
            } else {
                if (userService.userRegister(users)) {

                    request.setAttribute("msg", "注册成功！");
                    request.getRequestDispatcher("User/signup.jsp").forward(request, response);
                } else {

                    request.setAttribute("msg", "注册失败！");
                    request.getRequestDispatcher("User/signup.jsp").forward(request, response);
                }
            }
        } else {
            request.setAttribute("msg", "注册值不能为空！");
            request.getRequestDispatcher("User/signup.jsp").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }
}
